<template>
  <view class="move-container">
    <view class="form-section">
      <view class="form-item">
        <text class="label">条码:</text>
        <view class="barcode-input-row">
          <input
            v-model="barcodeInput"
            class="input"
            type="text"
            placeholder="请扫描或输入条码"
            @confirm="handleBarcodeInput"
          />
          <view class="barcode-count" @click="showBarcodeList = true">
            {{ formData.barcodes.length }}
          </view>
        </view>
      </view>
      <view class="form-item">
        <text class="label">路线号:</text>
        <input
          v-model="formData.routeNo"
          class="input"
          type="text"
          placeholder="请输入路线号"
        />
      </view>
      <view class="form-item">
        <text class="label">到货日期:</text>
        <input
          v-model="formData.arrivalDate"
          class="input"
          type="date"
          :value="formData.arrivalDate"
          @input="onDateChange"
        />
      </view>
      <view class="form-item">
        <text class="label">物料简称:</text>
        <input
          v-model="formData.materialName"
          class="input"
          type="text"
          placeholder="请输入物料简称"
        />
      </view>
      <view class="btn-group">
        <button @click="handleReset" class="btn btn-default">重置</button>
        <button @click="handleSubmit" class="btn btn-primary" :disabled="loading">
          <text v-if="loading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading ? '提交中...' : '合托要货' }}
        </button>
      </view>
      <!-- 条码列表弹窗 -->
      <view v-if="showBarcodeList" class="barcode-list-modal">
        <view class="barcode-list-content">
          <view class="barcode-list-title">已扫条码</view>
          <view v-for="(code, idx) in formData.barcodes" :key="idx" class="barcode-item">
            <text>{{ code }}</text>
            <button @click="removeBarcode(idx)" class="remove-btn">删除</button>
          </view>
          <button @click="showBarcodeList = false" class="close-btn">关闭</button>
        </view>
      </view>
    </view>
    <!-- 扫描条码展示区域 -->
    <view v-if="formData.barcodes.length" class="barcode-display-list">
      <view v-for="(code, idx) in formData.barcodes" :key="idx" class="barcode-display-item">
        {{ code }}
      </view>
    </view>
  </view>
</template>

<script>
import {moveStock} from '@/api/system/stock';

var main, receiver, filter;

export default {
  data() {
    return {
      formData: {
        barcodes: [],
        routeNo: '',
        arrivalDate: '',
        materialName: ''
      },
      barcodeInput: '',
      showBarcodeList: false,
      loading: false
    };
  },

  onLoad() {
    // 默认到货日期为今天
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    this.formData.arrivalDate = `${yyyy}-${mm}-${dd}`;
    this.initScan();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          console.log(code)
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    startScan() {
      /* #ifdef APP-PLUS */
      main.registerReceiver(receiver, filter);
      /* #endif */
    },

    stopScan() {
      /* #ifdef APP-PLUS */
      main.unregisterReceiver(receiver);
      /* #endif */
    },

    // 处理扫码结果
    handleScanResult(code) {
      // 条码多次扫码
      if (code && !this.formData.barcodes.includes(code)) {
        this.formData.barcodes.push(code);
      }
    },

    // 重置表单
    handleReset() {
      this.formData = {
        barcodes: [],
        routeNo: '',
        arrivalDate: '',
        materialName: ''
      };
      this.barcodeInput = '';
    },

    // 提交表单
    handleSubmit() {
      if (this.loading) return;
      if (!this.formData.barcodes.length) {
        this.$modal.msgError('请扫描或输入条码');
        return;
      }
      if (!this.formData.routeNo) {
        this.$modal.msgError('请输入路线号');
        return;
      }
      if (!this.formData.arrivalDate) {
        this.$modal.msgError('请选择到货日期');
        return;
      }
      if (!this.formData.materialName) {
        this.$modal.msgError('请输入物料简称');
        return;
      }
      this.loading = true;
      moveStock(this.formData)
        .then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess('提交成功');
            this.handleReset();
          } else {
            this.$modal.msgError(res.msg || '提交失败');
          }
        })
        .catch(error => {
          console.error('提交失败:', error);
          this.$modal.msgError('提交失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleBarcodeInput() {
      const code = this.barcodeInput.trim();
      if (code && !this.formData.barcodes.includes(code)) {
        this.formData.barcodes.push(code);
      }
      this.barcodeInput = '';
    },

    removeBarcode(idx) {
      this.formData.barcodes.splice(idx, 1);
    },

    onDateChange(e) {
      this.formData.arrivalDate = e.target.value;
    }
  }
}
</script>

<style lang="scss" scoped>
.move-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;

  .form-item {
    margin-bottom: 16px;

    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;

      .required {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }

    .input {
      width: 100%;
      height: 40px;
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #333;
    }
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;

  .btn {
    width: 48%;
    height: 40px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;

    &.btn-default {
      background-color: #f8f9fa;
      color: #666;
    }

    &.btn-primary {
      background-color: #4A90E2;
      color: #fff;

      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

.iconfont-spin {
  display: inline-block;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.barcode-input-row {
  display: flex;
  align-items: center;
  .input {
    flex: 1;
    margin-right: 8px;
  }
  .barcode-count {
    min-width: 32px;
    height: 32px;
    background: #ff4d4f;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: bold;
    cursor: pointer;
    border: 2px solid #fff;
    box-shadow: 0 0 0 2px #ff4d4f;
  }
}

// 扫描条码展示区域样式
.barcode-display-list {
  margin: 24px 0 0 0;
  padding: 0 8px;
}

.barcode-display-item {
  background: #f5f5f5;
  border: 2px solid #ff4d4f;
  color: #222;
  font-size: 22px;
  text-align: center;
  border-radius: 10px;
  margin-bottom: 12px;
  padding: 16px 0 12px 0;
  font-weight: 500;
}
</style>